<template>
  <div
    class="flex gap-2 h-full w-11/12"
    style="overflow: hidden; height: calc(100vh - 173px)"
    v-loading="loading"
  >
    <div style="min-width: 175px; height: calc(100vh - 205px)">
      <Button type="primary" @click="handleAddEmail" class="mb-2">
        <template #icon><plus-outlined /></template>
        新增
      </Button>
      <Scrollbar>
        <div class="flex-auto pr-1 mb-2">
          <ul>
            <li
              class="p-1 mb-1 overflow-hidden cursor-pointer source-componet-item"
              :class="{
                'source-componet-item-selected': currentEmail?.id == item.id,
              }"
              v-for="(item, index) in emailList"
              :key="index"
              @click="handleClickItem(item)"
            >
              <Dropdown :trigger="['contextmenu']">
                <div style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis">
                  <Tooltip :title="item.email">
                    {{ item.email }}
                  </Tooltip>
                </div>
                <template #overlay>
                  <Menu>
                    <MenuItem @click="handleDelete(item)">
                      <a style="color: red">删除</a>
                    </MenuItem>
                  </Menu>
                </template>
              </Dropdown>
            </li>
          </ul>
        </div>
      </Scrollbar>
    </div>
    <div class="flex-auto">
      <Scrollbar>
        <BasicForm @register="registerForm" />
        <div class="flex justify-center gap-2">
          <a-button type="primary" @click="handleSubmit()">确定</a-button>
        </div>
      </Scrollbar>
    </div>
    <SetupEmailAddModal
      @register="registerSetupEmailAddModal"
      @success="handleSuccessSetupEmailAddModal"
    />
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, inject } from 'vue';
  import { ScrollContainer } from '/@/components/Container';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './setupEmail.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { Scrollbar } from '/@/components/Scrollbar';
  import {
    getEmailEditEmail,
    getEmailListEmail,
    getEmailUpdateEmail,
    getEmailDelEmail,
  } from '/@/api/email/externalEmail';
  import { isEmpty } from '/@/utils/is';
  import { Dropdown, Menu, Button, Tooltip } from 'ant-design-vue';
  import SetupEmailAddModal from './setupEmailAddModal.vue';
  import { useModal } from '/@/components/Modal';
  import { PlusOutlined } from '@ant-design/icons-vue';
  const MenuItem = Menu.Item;
  const internalEmail = inject('internalEmail') as any;
  const currentEmail = ref<Recordable>({});
  const emailList = ref<Recordable[]>([]);
  const loading = ref(false);

  const [registerForm, { resetFields, validate, setFieldsValue }] = useForm({
    labelWidth: 200,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  //选中
  const handleClickItem = async (item) => {
    try {
      loading.value = true;
      currentEmail.value = await getEmailEditEmail({
        emailId: item.id,
      });
      loading.value = false;
      currentEmail.value.isSsl = currentEmail.value.ssl;
      currentEmail.value.isDelete = currentEmail.value.delete;
      currentEmail.value.isDefault = currentEmail.value.default;
      currentEmail.value.server = currentEmail.value.server
        ? currentEmail.value.server
        : 'smtp.qq.com';
      currentEmail.value.serverPop3 = currentEmail.value.serverPop3
        ? currentEmail.value.serverPop3
        : 'pop.qq.com';
      setFieldsValue({ ...currentEmail.value });
    } catch (error) {
      loading.value = false;
    }
  };

  const handleDelete = async (record) => {
    try {
      loading.value = true;
      await getEmailDelEmail({ emailId: record.id });
      loading.value = false;
      if (currentEmail.value.id == record.id) {
        currentEmail.value = {};
        resetFields();
      }
      handleSuccess();
    } catch (error) {
      console.error(error);
      loading.value = false;
    }
  };

  //条件
  const [registerSetupEmailAddModal, { openModal: openModalSetupEmailAddModal }] = useModal();
  //新增邮箱
  const handleAddEmail = () => {
    openModalSetupEmailAddModal(true, {});
  };

  const handleSuccessSetupEmailAddModal = async (data) => {
    handleClickItem(data);
    handleSuccess();
  };
  const handleSuccess = () => {
    fetch();
  };

  //确定
  const handleSubmit = async () => {
    try {
      const values = await validate();
      const formata = Object.assign({}, currentEmail.value, values);
      if (internalEmail.emailInfo.value.id) {
        formata.emailId = internalEmail.emailInfo.value.id;
      }
      delete formata.primaryKey;

      formata.isSsl = formata.isSsl ? 1 : 0;
      formata.isDelete = formata.isDelete ? 1 : 0;
      formata.isDefault = formata.isDefault ? 1 : 0;
      console.log('formata', formata);
      loading.value = true;
      await getEmailUpdateEmail(formata);
      loading.value = false;
      createMessage.success('操作成功');
      // handleSuccess();
    } catch (error) {
      loading.value = false;
    }
  };

  const fetch = async () => {
    try {
      loading.value = true;
      const res = await getEmailListEmail();
      loading.value = false;
      emailList.value = res || [];
      if (isEmpty(currentEmail.value) && emailList.value.length) {
        handleClickItem(emailList.value[0]);
      } else {
        internalEmail.setEmailInfoId();
      }
    } catch (error) {
      loading.value = false;
    }
  };
  onMounted(fetch);
</script>

<style scoped>
  .source-componet-item {
    padding: 8px 10px;
    border-radius: 4px;
  }
  .source-componet-item:hover {
    border-color: #0960bd;
    color: #0960bd;
    background-color: rgba(9, 96, 189, 0.06);
    /* border: 1px solid #d9d9d9; */
  }
  .source-componet-item-selected {
    border-color: #0960bd;
    color: #0960bd;
    background-color: rgba(9, 96, 189, 0.06);
  }
</style>
